package hot100;

public class Search {
    public int search(int[] nums, int target) {
        //思路就是尽量将target缩小到有序部分去查询
        if (nums.length == 0) return -1;
        //二分查找
        int left = 0,right = nums.length - 1;

        while (left <= right) {
            int mid = (left + right) / 2;
            if (target == nums[mid]) return mid;

            if (nums[0] <= nums[mid]) {
                //左侧是有序的
                if (target >= nums[0] && target <= nums[mid]) {
                    //在有序的范围内
                    right = mid - 1;
                } else {
                    //不在这个范围内，去右边找
                    left = mid + 1;
                }
            } else {
                //右侧是有序的
                if (target >= nums[mid] && target <= nums[nums.length - 1]) {
                    //在有序范围内找
                    left = mid + 1;
                } else {
                    //不在有序范围内
                    right = mid - 1;
                }
            }
        }
        return -1;
    }
}
